﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Catcher : MonoBehaviour {

    GameObject Player;
    Rigidbody rb;

    public float speed = 30.0f;
    public float p;

    Vector3 player_position;
    public Vector3 distance;
    public float dx,dz,abs_dx,abs_dz;
    public int flag, a, b;

    // Use this for initialization
    void Start () {
        Player = GameObject.Find("Player");
        rb = GetComponent<Rigidbody>();
    }
	
	// Update is called once per frame
	void Update () {
        //Breseham算法
        //坐标差值
        dx = Player.transform.position.x - rb.transform.position.x;
        dz = Player.transform.position.z - rb.transform.position.z;
        //取绝对值
        abs_dx = System.Math.Abs(dx);
        abs_dz = System.Math.Abs(dz);
        a = dx > 0 ? 1 : -1;
        b = dz > 0 ? 1 : -1;
        flag = 0;
        if (abs_dz >= abs_dx)
            //z轴上距离大于x轴
        {
            //将两值交换 使大值存储在 abs_dx 中
            float cur;
            cur = abs_dx;
            abs_dx = abs_dz;
            abs_dz = cur;
            flag = 1;//向z轴方向
        }
        p = 2 * abs_dz - abs_dx;
        distance = Vector3.zero;
        if (p >= 0)
        {
            if (flag == 0)
                distance = Vector3.forward * b;
            else
                distance = Vector3.right * a;
        }
        if (flag == 0)
            distance += Vector3.right* a;
        else
            distance += Vector3.forward* b;

        rb.AddForce(distance.normalized * speed);
    }
}
